# -*- coding:utf-8 -*-
# @Time  : 2019/11/18 19:28
# @Author: wangxb
'''
模块功能说明：
1、删除classes-dex2jar.src目录中的旧文件
2、解压classes-dex2jar.src.zip包到classes-dex2jar.src目录中
3、根据关键字wx查询classes-dex2jar.src目录中所有文件的微信ID
'''

import datetime
import os
import re
import zipfile

# 搜索关键字
from classes.jarOperation import getAPKPackage

# 搜索关键字
searchKey = 'wx'


def read_zipFile(zip_file_path, searchRootPath):
    '''
    解压ZIP文档中的所有文件到指定目录
    :return:
    '''
    try:
        zip_file_path = zip_file_path + os.sep + 'classes-dex2jar.src.zip'
        zFile = zipfile.ZipFile(zip_file_path, "r")
        # ZipFile.namelist(): 获取ZIP文档内所有文件的名称列表
        print("#######################Start to extract the zipFile#######################")
        for fileM in zFile.namelist():
            zFile.extract(fileM, searchRootPath)
        zFile.close()
        print("#######################Finished extracting the zipFile#######################")
    except BaseException as error:
        print("File is not a zip file")


class FindConetent(object):
    def __init__(self, root):
        """
             --初始化
        """
        self.root = root  # 文件树的根
        self.output_contents = []  # 查询到的字符串集合
        self.files = []  # 待匹配的文件集合

    @staticmethod
    def find_file(self):
        """
        --查找文件，即遍历文件树将查找到的文件放在文件集合中
        :return:
        """
        # python中的walk方法可以查找到所给路径下的所有文件和文件夹，这里只用文件
        for root, dirs, files in os.walk(self.root, topdown=True):
            for name in files:
                self.files.append(os.path.join(root, name))
                # print(os.path.join(root, name))
                #     print(os.path.join(root, name))

    @staticmethod
    def walk(self, outputPath, apk_file_path):
        """
        --逐一查找，并将结果存入result.txt文件中
        :param self:
        :return:
        """
        print("#######################Start searching the content#######################")
        testSame = ''
        for file_path in self.files:
            # print('file_path==' + file_path)
            # f = open(file_path, "r", encoding='ISO-8859-1')
            f = open(file_path, "r", encoding='utf-8')
            file_content = f.read()
            f.close()
            if searchKey:
                # 正则匹配，不区分大小写
                # searchObj = re.search(r'"[A-Za-z0-9]{,30}' + searchKey + '[A-Za-z0-9]{,30}"',
                #                       file_content,
                #                       re.M | re.I)
                pattern = re.compile(r'"' + searchKey + '[A-Za-z0-9]{,16}"')
                resultList = pattern.findall(file_content)
                resultLen = len(resultList)
                if resultLen > 0:
                    # print(resultList)
                    # print("file_path=" + file_path)
                    # searchResult = searchObj.group()
                    # print('group1==' + searchResult)
                    # searchString = searchResult.split('"')[1]
                    # 含有重复的微信ID，则不再添加到输出文件中
                    for searchString in resultList:
                        if hasNumbers(searchString) and testSame != searchString:
                            self.output_contents.append(searchString)
                            # isSame=searchObj.group()
                            testSame = searchString

                # searchObj = re.search(r'"' + searchKey + '[A-Za-z0-9]{,16}"',
                #                       file_content,
                #                       re.M | re.I)
                # if searchObj:
                #     print("file_path=" + file_path)
                #     searchResult = searchObj.group()
                #     print('group1==' + searchResult)
                #     searchString = searchResult.split('"')[1]
                #     # 含有重复的微信ID，则不再添加到输出文件中
                #
                #     if hasNumbers(searchString) and testSame != searchString:
                #         self.output_contents.append(searchObj.group())
                #         # isSame=searchObj.group()
                #         testSame = searchString

        try:
            result = '\n'
            result += datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '\n'
            # 获取包名称
            packageName = getAPKPackage(apk_file_path) + '\n'
            result += packageName
            for content in self.output_contents:
                length = len(content)
                if 14 < length < 30:
                    result += content + '\n'
            # f = open(outputPath, "a", encoding='utf-8')
            f = open(outputPath, "a", encoding='latin-1')
            result += datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '\n'
            print('searchResult:' + result)
            f.write(result)
            f.close()
        except IOError as msg:
            print("Error:", msg)
        else:
            print("#######################Finished searching the content#######################")


def examineDirectory(searchRootPath):
    '''
    判断搜索目录是否为空,不为空则删除目录中的文件
    :return:
    '''
    if os.path.exists(searchRootPath):
        print("#######################Start to delete the old directory#######################")
        for root, dirs, files in os.walk(searchRootPath, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
        # print("#######################Finishd deleting the old directory#######################")


def traverseDocument(searchRootPath):
    '''
    获取目录下的文件
    :return:
    '''
    apkList = []
    if os.path.exists(searchRootPath):
        for root, dirs, files in os.walk(searchRootPath, topdown=False):
            for name in files:
                # print(os.path.join(root, name))
                print(name)
                apkList.append(name)
    return apkList


def hasNumbers(inputString):
    '''
    验证字符串是否包含数字
    :param inputString:
    :return:
    '''
    return any(char.isdigit() for char in inputString)
# if __name__ == "__main__":
#     #删除之前目录中遗留的文件
#     examineDirectory()

# 解压zip文件
# read_zipFile()

# 根据关键字搜索指定路径下所有文件的内容
# findObj = FindConetent(searchRootPath)
# findObj.find_file(findObj)
# findObj.walk(findObj)
